import React, { useState } from 'react';
import { Layout, Menu, Button, Avatar, Dropdown, Space, Typography, Badge, Spin } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HomeOutlined,
  CloudDownloadOutlined,
  MessageOutlined,
  TeamOutlined,
  SettingOutlined,
  UserOutlined,
  LogoutOutlined,
  UploadOutlined,
  GiftOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { Link, useLocation, Outlet, Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useMessage } from '../context/MessageContext';

const { Header, Sider, Content } = Layout;
const { Text } = Typography;

const MainLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const { isAuthenticated, logout, user, isAdmin, loading } = useAuth();
  const { unreadCount } = useMessage();
  const location = useLocation();

  // 在加载状态时显示加载页面
  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '100vh' 
      }}>
        <Spin size="large" />
      </div>
    );
  }

  // 只有在不是加载状态且未认证时才重定向
  if (!loading && !isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  // 基础菜单项
  const baseMenuItems = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: <Link to="/">首页</Link>,
    },
    {
      key: '/torrents',
      icon: <CloudDownloadOutlined />,
      label: <Link to="/torrents">种子列表</Link>,
    },
    {
      key: '/upload',
      icon: <UploadOutlined />,
      label: <Link to="/upload">上传种子</Link>,
    },
    {
      key: '/requests',
      icon: <GiftOutlined />,
      label: <Link to="/requests">求种区</Link>,
    },
    {
      key: '/forum',
      icon: <TeamOutlined />,
      label: <Link to="/forum">论坛</Link>,
    },
    {
      key: '/messages',
      icon: <Badge count={unreadCount} size="small" offset={[10, 0]}>
        <MessageOutlined />
      </Badge>,
      label: <Link to="/messages">私信</Link>,
    },
    {
      key: '/tracker-status',
      icon: <ApiOutlined />,
      label: <Link to="/tracker-status">Tracker状态</Link>,
    },
  ];

  // 管理员菜单项
  const adminMenuItem = {
    key: '/admin',
    icon: <SettingOutlined />,
    label: '管理后台',
    children: [
      {
        key: '/admin/users',
        label: <Link to="/admin/users">用户管理</Link>,
      },
      {
        key: '/admin/torrents',
        label: <Link to="/admin/torrents">种子管理</Link>,
      },
      {
        key: '/admin/stats',
        label: <Link to="/admin/stats">统计信息</Link>,
      },
      {
        key: '/admin/invitations',
        label: <Link to="/admin/invitations">邀请码管理</Link>,
      },
      {
        key: '/admin/password-test',
        label: <Link to="/admin/password-test">密码测试</Link>,
      },
    ],
  };

  // 根据用户权限组合菜单
  const menuItems = isAdmin() ? [...baseMenuItems, adminMenuItem] : baseMenuItems;

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: <Link to="/profile">个人资料</Link>,
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: <Link to="/settings">设置</Link>,
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: logout,
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div style={{ 
          height: 32, 
          margin: 16, 
          background: 'rgba(255, 255, 255, 0.3)',
          borderRadius: 6,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'white',
          fontWeight: 'bold'
        }}>
          {collapsed ? 'PT' : 'PT站点'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <Header style={{ 
          padding: '0 16px', 
          background: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          boxShadow: '0 1px 4px rgba(0,21,41,.08)'
        }}>
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{
              fontSize: '16px',
              width: 64,
              height: 64,
            }}
          />
          
          <Space>
            {/* 显示未读消息数量 */}
            {unreadCount > 0 && (
              <Link to="/messages">
                <Badge count={unreadCount} size="small">
                  <Button type="text" icon={<MessageOutlined />}>
                    未读消息
                  </Button>
                </Badge>
              </Link>
            )}
            <Text>欢迎回来！</Text>
            <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
              <Space style={{ cursor: 'pointer' }}>
                {user?.avatar ? (
                  <img
                    src={`http://localhost:8080${user.avatar}`}
                    alt="用户头像"
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: '50%',
                      objectFit: 'cover'
                    }}
                    onError={(e) => {
                      // 头像加载失败时显示默认头像
                      console.log('头像加载失败，使用默认头像');
                      (e.target as HTMLImageElement).style.display = 'none';
                      const fallback = (e.target as HTMLImageElement).nextElementSibling as HTMLElement;
                      if (fallback) {
                        fallback.style.display = 'inline-block';
                      }
                    }}
                  />
                ) : null}
                <Avatar 
                  icon={<UserOutlined />} 
                  style={{ 
                    display: user?.avatar ? 'none' : 'inline-block',
                    marginRight: 0
                  }}
                />
                <Text>{user?.username || '用户'}</Text>
              </Space>
            </Dropdown>
          </Space>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: '#fff',
            borderRadius: 6,
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout; 